<script lang="ts">
import {defineComponent, onMounted, reactive, ref, toRefs} from 'vue'
import PageTable from "@/components/pageTable/pageTable.vue";
import {axiosHttp} from "@/util/axios.ts";
import SaveForm from "@/components/saveForm/saveForm.vue";
import {SaveFormConfig} from "@/components/saveForm/types/type.ts";
import IconChange from "@/components/iconChange/icon-change.vue";
import {sendGlobalMessage} from "@/hooks/globalmessage.ts";

export default defineComponent({
  name: 'menu',
  components: {IconChange, SaveForm, PageTable},

  setup() {

    const data = reactive({
      tableData: [],
      saveForm: {
        pid: "",
        type: 0,
        title: "",
        icon: "",
        permission: "",
        route: "",
        permissionLevel: ''
      },
      title: "",
      currentGroup: 'add',
      saveFormConfigListMenu: <SaveFormConfig[]>[
        new SaveFormConfig().buildLabel("上级菜单").buildProp("pid").buildCustomSlotName("saveFormPidSlot"),
        new SaveFormConfig().buildLabel("类型").buildProp("type").buildCustomSlotName("saveFormTypeSlot"),
        new SaveFormConfig().buildLabel("标题").buildProp("title"),
        new SaveFormConfig().buildLabel("图标").buildProp("icon").buildCustomSlotName("saveFormIconSlot"),
        new SaveFormConfig().buildLabel("路由").buildProp("route"),
      ],
      saveFormConfigListPerm: <SaveFormConfig[]>[
        new SaveFormConfig().buildLabel("上级菜单").buildProp("pid").buildCustomSlotName("saveFormPidSlot"),
        new SaveFormConfig().buildLabel("类型").buildProp("type").buildCustomSlotName("saveFormTypeSlot"),
        new SaveFormConfig().buildLabel("权限值").buildProp("permission"),
        new SaveFormConfig().buildLabel("权限等级").buildProp("permissionLevel").buildCustomSlotName("saveFormPermLevelSlot"),
      ],
      detailUrl: "/menu/detail",
      saveUrl: "/menu/save",
      typeList: [
        {
          label: "菜单",
          value: 0
        },
        {
          label: "权限",
          value: 1
        },
      ],
      pidList: [
        {
          id: 0,
          title: "无上级"
        },
        {
          id: 1,
          title: "系统管理"
        }
      ],
      permLevelList: [
        {
          label: "页面级",
          value: 0
        },
        {
          label: "组件级",
          value: 1
        },
        {
          label: "元素级",
          value: 2
        },
      ]
    })

    const methods = {
      async init() {
        let res = await axiosHttp.post("/menu/tree/list")
        if (res.isSuccess()) {
          data.tableData = res.data
        }
        console.log(res)
      },
      save(id: string, detail: boolean = false) {
        console.log(id)
        if (id) {
          data.title = "编辑菜单/权限"
          data.currentGroup = 'update'
          refs.saveFormRef.value.init(id)
        } else {
          data.currentGroup = "add"
          data.title = '新增菜单/权限'
          refs.saveFormRef.value.init()
        }


      },
      changeIcon(icon: string) {
        console.log(icon)
        data.saveForm.icon = icon
      },
      changeType(type: number) {

        if (type == data.typeList[0].value) {
          //菜单 清空权限相关数据
          data.saveForm.permission = ""
          data.saveForm.permissionLevel = ""
        } else {
          //权限 清空菜单相关数据
          data.saveForm.title = ""
          data.saveForm.icon = ""
          data.saveForm.route = ""
        }
        refs.saveFormRef.value.clearRulesAsync()
      },
      async deleteOne(id: string) {
        let res = await axiosHttp.delete("/menu/delete/" + id)
        if (res.isSuccess()) {
          sendGlobalMessage("删除成功")
          await methods.init()
        }
      },
      async updateStatus(row: any) {
        let res = await axiosHttp.post("/menu/updateStatus", {
          id: row.id,
          status: row.status == 0 ? 1 : 0
        })
        if (res.isSuccess()) {
          await methods.init()
          sendGlobalMessage("修改状态成功")
        }
      },
      saveSuccess() {
        sendGlobalMessage("保存成功")
        methods.init()
      },
      beforeClose() {

      },
      updateForm(form: any) {
        data.saveForm = form
      }
    }
    onMounted(() => {
      methods.init()
    })

    const validators = {}


    const rules = reactive({
      commonRules: {
        pid: [
          {required: true, message: "请选择上级菜单，没有则选择无上级菜单", trigger: 'change'}
        ],
        type: [
          {required: true, message: "请选择分类(菜单/权限)", trigger: 'change'}
        ]
      },
      saveMenuRules: {
        title: [
          {required: true, message: "请输入菜单标题", trigger: 'blur'}
        ],
        icon: [
          {required: true, message: "请选择icon", trigger: 'change'}
        ]
      },
      savePernRules: {
        permission: [
          {required: true, message: "请输入权限值", trigger: 'blur'}
        ],
        permissionLevel: [
          {required: true, message: "请选择权限分级", trigger: 'change'}
        ]
      }
    })

    const refs = {
      saveFormRef: ref()
    }


    return {
      ...toRefs(data),
      ...methods,
      ...validators,
      ...rules,
      ...refs
    }
  }
})
</script>

<template>
  <el-row>
    <el-button type="text" @click="save('')">添加</el-button>
  </el-row>
  <el-table :data="tableData" empty-text="暂无数据" :row-key="'id'">
    <el-table-column prop="title" label="标题" align="center"></el-table-column>
    <el-table-column prop="type" label="类型" align="center">
      <template #default="{row}">
        {{ row.type == 0 ? '菜单' : "权限" }}
      </template>
    </el-table-column>
    <el-table-column prop="icon" label="图标" align="center">
      <template #default="{row}">
        <el-icon size="20" color="#1677ff">
          <component :is="row.icon"/>
        </el-icon>
      </template>
    </el-table-column>
    <el-table-column prop="route" label="路由" align="center">
      <template #default="{row}">
        {{ row.route || "-"}}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态" align="center">
      <template #default="{row}">
        {{ row.status == 0 ? '禁用' : '启用' }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{row}">
        <el-button type="text" @click="save(row.id)">编辑</el-button>
        <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="WarningFilled"
            icon-color="#e64646"
            title="确定要删除该条数据吗?"
            @confirm="deleteOne(row.id)"
            @cancel="()=>{}"
        >
          <template #reference>
            <el-button type="text">删除</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="WarningFilled"
            icon-color="#e64646"
            :title="'确定要'+(row.status==1?'禁用':'启用')+'该菜单?'"
            @confirm="updateStatus(row)"
            @cancel="()=>{}"
        >
          <template #reference>
            <el-button type="text">{{ row.status == 1 ? '禁用' : '启用' }}</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <save-form
      ref="saveFormRef"
      v-model:save-form="saveForm"
      :save-form-config-list="saveForm.type==0?saveFormConfigListMenu:saveFormConfigListPerm"
      :title="title"
      :detail-url="detailUrl"
      :save-url="saveUrl"
      :current-group="currentGroup"
      :rules="saveForm.type==0?{...commonRules,...saveMenuRules}:{...commonRules,...savePernRules}"
      @save-success="saveSuccess"
      @before-close="beforeClose"
      @update-form="updateForm"
  >
    <template #saveFormPidSlot>
      <el-select placeholder="请选择上级菜单" v-model="saveForm.pid">
        <el-option v-for="(item,index) in pidList" :key="item.id" :label="item.title" :value="item.id">
        </el-option>
      </el-select>
    </template>
    <template #saveFormTypeSlot>
      <el-select placeholder="请选择分类" v-model="saveForm.type" @change="changeType">
        <el-option v-for="(item,index) in typeList" :key="item.value" :label="item.label" :value="item.value">

        </el-option>
      </el-select>
    </template>
    <template #saveFormIconSlot>
      <icon-change :model-value="saveForm.icon" :title="'请选择菜单图标'"
                   @change="changeIcon"
      >

      </icon-change>
    </template>
    <template #saveFormPermLevelSlot>
      <el-select placeholder="请选择权限分级" v-model="saveForm.permissionLevel">
        <el-option v-for="(item,index) in permLevelList" :key="item.value"
                   :label="item.label"
                   :value="item.value"
        ></el-option>
      </el-select>
    </template>
  </save-form>
</template>

<style scoped>

</style>